<template>
    <el-dialog v-model="show"  title="添加用户" @close="emit('hide')">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item label="类型名称" prop="name" label-width="100px">
                <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="emit('hide')">取消</el-button>
                <el-button type="primary" @click="sureFn"> 确定 </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { user } from '@/api';
import { ElMessage, FormInstance } from 'element-plus';
import { reactive, ref,watch } from 'vue';

const form = reactive<any>({
    name: ''
})
const props = defineProps({
    show: {
        type: Boolean,
        default: true,
    },
    id: {
        type: Number,
        default: 0,
    },
    data: {
        type: String,
        defaule:''
    }

});

const rules = {
    name: [
        { required: true, message: "请输入类型名称", trigger: "blur" },
    ]
}

const emit = defineEmits(["hide", "refresh"])

// 点击确定
const formRef = ref<FormInstance>()

const sureFn = () => {
    formRef.value?.validate((valid: boolean) => {
        if (valid) {
            if (props.id !== 0) {
                user.IProductEditApi(props.id,form).then((res) => {
                    console.log(1);
                    
                    if (res.code === 200) {
                        ElMessage.success("修改成功")                               
                                emit("hide")                                
                                emit("refresh")
                    }
                })
            } else {

                
                // 新增类型，发送新增请求
                user.IProductCreateApi(form).then((res) => {
                if (res.code === 200) {
                    ElMessage.success("属性添加成功！")
                    emit("hide")
                    emit("refresh")
                }
            })
            }
        } else {
            return false
        }

    });
};

watch(
    () => props.id,
    () => {
        if (props.id === 0) {
            return
        }
        form.name = props.data
    }
)
</script>

<style scoped>

</style>